package cn.memedai.router.demo.webview;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.util.AttributeSet;
import android.webkit.WebSettings;
import android.webkit.WebView;

import java.io.File;

public class CustomWebView extends WebView {
    private static final int MAX_CACHE_SIZE = 1024 * 1024 * 4;
    private Context mContext;
    private OnScrollChangeListener mOnScrollChangeListener;

    public CustomWebView(Context context) {
        super(context);
        initSetting(context);
    }

    public CustomWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initSetting(context);
    }

    public CustomWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initSetting(context);
    }

    private void initSetting(Context context) {
        this.mContext = context;
        removeJavascriptInterface("searchBoxJavaBridge_");
        removeJavascriptInterface("accessibility");
        removeJavascriptInterface("accessibilityTraversal");
        WebSettings settings = getSettings();
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setJavaScriptEnabled(true);
        settings.setAllowFileAccess(true);
        settings.setPluginState(WebSettings.PluginState.ON);
        settings.setSaveFormData(false);
        settings.setLoadsImagesAutomatically(true);
        settings.setSavePassword(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        settings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        settings.setDisplayZoomControls(false);
        settings.setBuiltInZoomControls(true);
        settings.setDomStorageEnabled(true);
        settings.setDatabaseEnabled(true);
        settings.setAppCacheMaxSize(MAX_CACHE_SIZE);
        settings.setAppCachePath(getExternalCacheDir(context));
        settings.setAllowContentAccess(true);
        settings.setAllowFileAccess(true);
        settings.setAppCacheEnabled(true);
        // 若有网络，则实时网上获取，如无网络，显示本地缓存
        if (isNetworkConnected(context)) {
            settings.setCacheMode(WebSettings.LOAD_NO_CACHE);  //设置 缓存模式
        } else {
            settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);  //设置 缓存模式
        }
    }

    /**
     * 释放webView.
     */
    public void releaseWebView() {
        removeAllViews();
        destroy();
        setWebViewClient(null);
        setWebChromeClient(null);
        setDownloadListener(null);
    }

    @Override
    public void loadUrl(String url) {
        super.loadUrl(url);
    }

    private String getExternalCacheDir(Context context) {
        File dataDir = new File(context.getCacheDir().getAbsolutePath(), "web");
        if (!dataDir.exists()) {
            if (!dataDir.mkdirs()) {
                return context.getCacheDir().getAbsolutePath();
            }
        }
        return dataDir.getAbsolutePath();
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        if (mOnScrollChangeListener == null) {
            return;
        }
        // webview的高度
        float webTotalHeight = getContentHeight() * getScale();
        // 当前webview的高度
        float webCurrentHeight = getHeight() + getScrollY();
        if (Math.abs(webTotalHeight - webCurrentHeight) < 5) {
            mOnScrollChangeListener.onPageEnd(l, t, oldl, oldt);
        } else if (getScrollY() == 0) {
            //处于顶端
            mOnScrollChangeListener.onPageTop(l, t, oldl, oldt);
        } else {
            mOnScrollChangeListener.onScrollChanged(l, t, oldl, oldt);
        }
    }

    public void setOnScrollChangeListener(OnScrollChangeListener listener) {
        this.mOnScrollChangeListener = listener;
    }

    public interface OnScrollChangeListener {
        void onPageEnd(int l, int t, int oldl, int oldt);
        void onPageTop(int l, int t, int oldl, int oldt);
        void onScrollChanged(int l, int t, int oldl, int oldt);
    }

    public boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }
}
